#define _CRT_SECURE_NO_WARNINGS 1
#include "SList.h"


SLTNode* BuySLTNode(SLTDataType x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	if (newnode == NULL)
	{
		perror("malloc");
		return NULL;
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}

void SLTPrint(SLTNode* phead)
{
	SLTNode* cur = phead;
	while(cur)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

void SLTPushBack(SLTNode** ps, SLTDataType x)
{
	assert(ps);
	SLTNode* newnode = BuySLTNode(x);
	if (*ps == NULL)
	{
		*ps = newnode;
	}
	else
	{
		SLTNode* tail = *ps;
		while (tail->next)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}
void SLTPopBack(SLTNode** ps)
{
	assert(ps);
	assert(*ps);
	SLTNode* tail = *ps;
	if (tail->next == NULL)
	{
		free(ps);
		ps = NULL;
	}
	else
	{
		while (tail->next->next)
		{
			tail = tail->next;
		}
		free(tail->next);
		tail->next = NULL;
	}
}
void SLTPushFront(SLTNode ** ps, SLTDataType x)
{
	assert(ps);
	SLTNode* newnode = BuySLTNode(x);
	newnode->next = *ps;
	*ps = newnode;
}

void SLTPopFront(SLTNode** ps)
{
	SLTNode* del = *ps;
	*ps =del->next;
	free(del);
	del = NULL;
}

SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
	while (phead)
	{
		if (phead->data == x)
		{
			return phead;
		}
		phead = phead->next;
	}
	return NULL;
}

void SLTInsert(SLTNode** ps, SLTNode* pos, SLTDataType x)
{
	assert(ps);
	assert(pos);
	SLTNode* newnode = BuySLTNode(x);
	SLTNode* prev = *ps;
	if (pos == *ps)
	{
		SLTPushFront(ps, x);
	}
	else
	{
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		newnode->next = prev->next;
		prev->next = newnode;
	}
}

void SLTErase(SLTNode** ps, SLTNode* pos)
{
	assert(ps);
	assert(pos);
	SLTNode* prev = *ps;
	if (pos == *ps)
	{
		SLTPopFront(ps);
	}
	else
	{
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
		pos = NULL;
	}
}

void SLTInsertAfter(SLTNode* pos, SLTDataType x)
{
	assert(pos);
	SLTNode* newnode = BuySLTNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

void SLTEraseAfter(SLTNode* pos)
{
	assert(pos);
	assert(pos->next);
	SLTNode* del = pos->next;
	pos->next = pos->next->next;
	free(del);
}